package aqv

import aqv.PoliticalParty;
import aqv.PoliticalPartyRole;

class User {

	transient springSecurityService

	String username
	String password
	boolean enabled = true
	boolean accountExpired
	boolean accountLocked
	boolean passwordExpired
	
	static transients = ['springSecurityService']
	
	/* CUSTOM ATTR */
	String firstName
	String lastName
	String email
	PoliticalParty politicalParty
	PoliticalPartyRole politicalPartyRole
	String apiKey
	Boolean confirm

	static belongsTo = [PoliticalParty, PoliticalPartyRole]

	static constraints = {
		username blank: false, unique: true
		password blank: false
		password blank:false
		firstName blank:false
		lastName blank:false
		politicalParty nullable:true
		politicalPartyRole nullable:true
		email blank:false, unique: true
	}

	static mapping = {
		password column: '`password`'
		tablePerHierarchy false
		politicalParty lazy: false
		politicalPartyRole lazy: false
	}

	Set<Role> getAuthorities() {
		UserRole.findAllByUser(this).collect { it.role }
	}

	def beforeInsert() {
		encodePassword()
	}

	def beforeUpdate() {
		if (isDirty('password')) {
			encodePassword()
		}
	}

	protected void encodePassword() {
		password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
	}
	
	
}
